// pages/index/enclosure/enclosure.js
let app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    user: '',
    key: '',
    latitudeData: 0,
    longitudeData: 0,
    nameData: '我的位置',
    listShop: [],
    cateringType: '',
  },

  searchChange(event) {
    this.setData({
      key: event.detail
    })
  },
  //搜索
  searchSearch(event) {
    this.getNearestShop(this.data.key);
  },

  //绑定
  onConfirm(event) {
    let _this = this;
    let shopId = event.currentTarget.dataset.id;
    let centreId = event.currentTarget.dataset.centreid;
    let tXiaoqu = event.currentTarget.dataset.txiaoqu;
    let shopInfo = event.currentTarget.dataset.info;
    //校验是否传了外卖type过来，如果没传则可以随便选择门店，如果传了，则只能等于2且status == 100时，才能点
    console.log(_this.data.cateringType);
    if (_this.data.cateringType != 2) {
      wx.setStorageSync("tempCentreId", centreId);
      wx.setStorageSync('shopInfo', JSON.stringify(shopInfo));
      //未登录选择门店，保存门店id
      if (_this.data.user.id == null) {
        wx.switchTab({
          url: '/pages/index/index',
        })
      } else {
        _this.data.user.upshopTid = shopId;
        _this.data.user.centreId = centreId;
        // _this.data.user.tXiaoqu = tXiaoqu;
        wx.setStorageSync('userInfo', JSON.stringify(_this.data.user));
        console.log(_this.data.cateringType);
        if (_this.data.cateringType) {
          wx.redirectTo({
            url: '/subIndex/index/iron-one-scroll/iron-one-scroll?productType=6&cateringType=' + _this.data.cateringType
          })
        } else {
          wx.switchTab({
            url: '/pages/index/index',
          })
        }
      }
    } else {
      if (_this.data.cateringType == '2' && event.currentTarget.dataset.status != 100) {
        wx.setStorageSync("tempCentreId", centreId);
        wx.setStorageSync('shopInfo', JSON.stringify(shopInfo));
        //未登录选择门店，保存门店id
        if (_this.data.user.id == null) {
          wx.switchTab({
            url: '/pages/index/index',
          })
        } else {
          _this.data.user.upshopTid = shopId;
          _this.data.user.centreId = centreId;
          // _this.data.user.tXiaoqu = tXiaoqu;
          wx.setStorageSync('userInfo', JSON.stringify(_this.data.user));
          console.log(_this.data.cateringType);
          if (_this.data.cateringType) {
            wx.redirectTo({
              url: '/subIndex/index/iron-one-scroll/iron-one-scroll?productType=6&cateringType=' + _this.data.cateringType
            })
          } else {
            wx.switchTab({
              url: '/pages/index/index',
            })
          }
        }
      }
    }

  },

  //获取列表
  getNearestShop(key) {
    let _this = this;
    app.requestUrl({
      method: 'GET',
      url: '/wxapi/shop/newNearest',
      data: {
        teamName: key || '',
        longitude: _this.data.longitudeData,
        latitude: _this.data.latitudeData,
        limit: 50,
        centreId: app.globalData.loginCentreId,
        flag: 2,//1平台 2商户
        cateringtype: _this.data.cateringType
      },
      load: 1
    }).then((res) => {
      let dl = res.data.data;
      let temp = [];
      dl.forEach(shop => {
        shop.distance = _this.getDistance(_this.data.latitudeData, _this.data.longitudeData, shop.lat, shop.lng).toFixed(2);
        temp.push(shop);
      })
      _this.setData({
        listShop: temp
      })
    })
  },

  //距离xxx公里方法
  getDistance(lat1, lng1, lat2, lng2) {
    var radLat1 = lat1 * Math.PI / 180.0;
    var radLat2 = lat2 * Math.PI / 180.0;
    var a = radLat1 - radLat2;
    var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
      Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    s = s * 6378.137; // EARTH_RADIUS;
    s = Math.round(s * 10000) / 10000;
    return s;
  },

  //点击地址调用地图
  call_map: function (e) {
    let _this = this;
    if (e != '' && e != undefined) {
      let status = e.currentTarget.dataset.status;
      wx.chooseLocation({////选择位置
        success: function (res) {
          _this.setData({
            nameData: res.name,
            latitudeData: res.latitude,
            longitudeData: res.longitude,
          })
          _this.getNearestShop();
        }
      })
    } else {
      wx.getLocation({////获取当前位置信息
        //定位类型 wgs84, gcj02
        // wgs84 返回 gps 坐标，gcj02 返回可用于wx.openLocation的坐标
        type: 'wgs84',
        //获取位置成功
        success: function (res) {
          // wx.chooseLocation({////选择位置
          //   success: function (res) {
          //     _this.setData({
          //       nameData: res.name,
          //       latitudeData: res.latitude,
          //       longitudeData: res.longitude,
          //     })
          //     _this.getNearestShop();
          //   }
          // })
          _this.setData({
            nameData: res.name,
            latitudeData: res.latitude,
            longitudeData: res.longitude,
          })
          _this.getNearestShop();
        },
        //获取位置失败
        fail: function (err) {
          console.log("拒绝访问地址权限")
          _this.getNearestShop();
        },
        //接口调用结束的回调函数（调用成功、失败都会执行）
        complete: function (info) {
          console.log("完成")
        },
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options);
    let _this = this;
    _this.setData({
      user: app.getUser(),
      //餐饮类型：1堂食，2外卖，3自提
      cateringType: options.cateringType
    })
    _this.call_map();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})